import { Injectable, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';
import { PrismaService } from '../prisma/prisma.service';
import { ApiResponse } from 'src/common/reponse.interface'; // 引入统一响应格式
@Injectable()
export class AuthService {
  constructor(
    // 注入 PrismaService 和 JwtService
    private prisma: PrismaService,
    private jwtService: JwtService,
  ) {}

  // 用户登录验证
  async login(username: string, password: string): Promise<ApiResponse<any>> {
    // 查询用户
    const user = await this.prisma.user.findUnique({
      where: { username },
    });

    // 如果用户不存在，则抛出 BadRequestException 异常
    if (!user) {
      throw new BadRequestException('没有该用户');
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    // 如果密码不正确，则抛出 BadRequestException 异常
    if (!isPasswordValid) {
      throw new BadRequestException('密码错误');
    }

    // 生成 JWT
    const payload = { username: user.username, sub: user.id };
    const accessToken = this.jwtService.sign(payload);

    // 返回 JWT
    return {
      statusCode: 200,
      message: '登录成功',
      data: accessToken,
    }; // 返回 JWT
  }

  // 用户注册
  async register(username: string, password: string, roleId: number) {
    // 哈希密码
    const hashedPassword = await bcrypt.hash(password, 10);
    // 创建用户
    const user = await this.prisma.user.create({
      data: {
        username,
        password: hashedPassword,
        role: {
          connect: { id: roleId },
        },
      },
    });

    return user;
  }
}
